import { makeAutoObservable, action, } from 'mobx';
import dayjs from "dayjs";
import BleConnection from '~/utils/ble/connect';
import * as cmd from '~/utils/ble/cmd';
import { getHandleBleDataResponse } from '~/utils/ble/getBleData';
import { getDeviceWriteInfo, deviceGiveStatus, writeOfflineCourse, getUserOfflineCourse } from '~/api/deviceApi'
import { getLaserTreatmentParameterOnline, setLaserTreatmentParameterOnline, getBleCurrentCourse, getBleDeviceInfo, getBleEQ, syncTime, getBleHeartAutoState, LaserTreatmentInterval, setEbiValue, setLaserTimeOut, setLaserTreatmentParameters } from '~/utils/ble/application';
import { delay } from '~/utils/utils';
import { getDeviceDataHead } from '~/utils/ble/getBleData';
import { parseTherapyPacketsSeparately } from '~/utils/helpers';
import { offlineCourseDevices } from '~/utils/deviceMenues';
import webSocketStore from './webSocketStore';
import userStore from './userStore';


let result: any = null; // 处理后的数据
const Bleconnect = BleConnection.getInstance();
const statusMap = {
    0: '操作成功',
    1: '操作失败',
    2: '操作无效',
    3: '操作占用',
    4: '未发现',
    5: '重复操作',
    6: '充电保护',
    7: "设备低电",
    8: "没有找到",
};
interface BindDeviceInfo {
    bind_status: string,
    bind_time: string,
    connect_status: string,
    course_status: string,
    device_alias: string // 设备别名
    device_code: string, // 设备型号
    device_id: string, // 设备ID
    device_image: string, // 设备图片
    device_name: string, // 设备名
    device_sn: string,  // 设备SN编号
    firmware_sn: string,
    id: string,
    update_status: string,
}

type DeviceType = {
    device_image: string;
    firmware_code: string;
}[];

type BindDevice = BindDeviceInfo[];

interface SerachDeviceInfo {
    device_sn: string,
    id: string,
    siginal: string,
    device_code: string,
    isCicle: string,
    device_name: string,
    prevName: string,
    rssi: string,
    device_image: string,
    firmware_code: string,
}
type SerachDevice = SerachDeviceInfo[];
interface Device {
    deviceTypeList: DeviceType, // 统计所有设备类型
    connectDevice: any, // 设备连接单个记录
    searchDevices: SerachDevice, // 搜索到的设备
    userBindDevice: BindDevice // 用户绑定的设备
    deviceStatus: number,// 手机蓝牙状态 1、打开 0、关闭
    connectedDeviceStatus: number,// 0、断开 1、连接成功
}

type PerformAction = 'connectOnly' | 'connectAndUpload'
type BleCallback = (err: Error | null, res: any | null) => void;

class DeviceStore {
    dfuDevice = { id: '', device_sn: '', device_code: '' };//dfu升级失败的设备
    device = { connectedDeviceStatus: 0 } as Device;
    bleSearchbBindDevices = [] // 搜索用户绑定的设备列表
    remoteInfo = {
        type: "",
        device_sn: "",
        subDevice_sn: "",
        device_code: "",
    };
    successWifi: number = -1;
    laser = {
        laserParamsResult: -1, // 设置手动激光参数
        laserStatus: -1, // 激光开启/关闭状态
        isOpenStatus: false,//激光已经开启
        power: 2, // 激光强度
        duration: 16 // 激光时长
    };
    heart = {
        heartStatus: false, // 心率开启状态
        heartValue: 0 // 心率值
    };
    blood = {
        bloodStatus: false,// 血压开启状态
        systolic: 0, // 收缩压
        diastolic: 0, // 舒张压
        heartrate: 0, // 心率
        microcirculation: 0, // 微循环
    };
    screenStatus = 0; // 抬手亮屏设置
    themeIndex = -1; // 设置的表盘主题
    calibration = {
        systolic: 120, // 收缩压
        diastolic: 80 // 舒张压
    };
    watchTimeData = [0, 8, 0, 0, 12, 16, 0, 16, 50];// 默认设置血压定时时间戳
    bloodSleepData = [0, 21, 0, 6, 0, 60];// 默认设置血压睡眠模式参数
    course = {
        writeCourseStatus: false, // 写入疗程状态
        courseIntervalStatus: false,// 疗程间隙
    }; // 疗程设置
    isTagStatus = -1 // 设置标签是否成功
    callbacks: any = []; // 存储回调函数
    connectDeviceInfo = {
        factorySerialNumber: '',
        hardwareVersion: "",
        productModle: "",
        manufacturerName: '',
        firmwareVersion: '',
        protocolStackVersion: '',
        eq: 0, // 设备电量
    }; // 获取的连接设备信息
    shockStatus = false;// 睡眠模式状态
    enableHeartAndBlood = false; // 获取的法规血氧心率开关状态
    laserPowerStatus = 1;// 获取智能激光保护协议状态
    isLowPattern = { modeStartNum: 0, modeEndNum: 0 };// 计时模式返回的状态
    zHeartRateDataStatus = 0// 自动心率监测状态
    sleepDate = [0, 0, 0, 0]// 睡眠时间
    colockData = [0, 127, 13, 30, 0, 127, 15, 0, 0, 127, 18, 0] // 闹钟时间
    uploadProgress = 0 // 上传数据进度
    performAction = 'connectOnly' as PerformAction // connectOnly只连接、connectAndUpload连接并上传数据
    currentCallback: BleCallback | null = null; // 存储外部回调 = null
    deviceWriteInfo = {
        remaining_days: 0,
        parameter_list: [],
        course_data: {
            course_type_sn: '',
            course_cycle_work_days: '',
            course_cycle_rest_days: '',
            use_day: 0,
        }
    } // 服务器存的设备信息
    ASCIIDic = {
        38: '&',
        46: ".",
        48: '0',
        49: '1',
        50: '2',
        51: '3',
        52: '4',
        53: '5',
        54: '6',
        55: '7',
        56: '8',
        57: '9',
        65: 'A',
        66: 'B',
        67: 'C',
        68: 'D',
        69: 'E',
        70: 'F',
        71: 'G',
        72: 'H',
        73: 'I',
        74: 'J',
        75: 'K',
        76: 'L',
        77: 'M',
        78: 'N',
        79: 'O',
        80: 'P',
        81: 'Q',
        82: 'R',
        83: 'S',
        84: 'T',
        85: 'U',
        86: 'V',
        87: 'W',
        88: 'X',
        89: 'Y',
        90: 'Z',
        97: 'a.js',
        98: 'b',
        99: 'c',
        100: 'd',
        101: 'e',
        102: 'f',
        103: 'g',
        104: 'h',
        105: 'i',
        106: 'j',
        107: 'k',
        108: 'l',
        109: 'm',
        110: 'n',
        111: 'o',
        112: 'p',
        113: 'q',
        114: 'r',
        115: 's',
        116: 't',
        117: 'u',
        118: 'v',
        119: 'w',
        120: 'x',
        121: 'y',
        122: 'z',
    }
    bleState = []
    wifiRealUploadStatus = 0 // wifi实时上传开关
    wifiTimingData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] // wifi定时上传开关,时间
    packets: any = []; //离线疗程
    offlineBleCourses: any = [];// 硬件当前的离线疗程
    currentBleCourseSn = ''// 获取硬件当前使用的疗程
    isConnect = false
    courseOfflineDataLength = 0
    replyCount = 0
    isWriteOffline = false
    offlineActionType = 'open'
    bleDeviceCourseStatus = 0
    constructor() {
        this.currentCallback = null;
        makeAutoObservable(this, {
            updateSuccessWifi: action// mark th
        });
    }
    onUploadProgress(progress) {
        this.uploadProgress = progress
    }
    signDfuDevice(res) {
        this.dfuDevice = res
    }
    getStatusText = (state) => {
        return statusMap[state] || '未知状态';
    };
    // 清除远程连接的状态
    cleanStatus() {
        this.device.connectDevice = {}
        this.device.connectedDeviceStatus = 0
        this.successWifi = -1
        this.deviceWriteInfo = {
            remaining_days: 0,
            parameter_list: [],
            course_data: {
                course_type_sn: '',
                course_cycle_work_days: '',
                course_cycle_rest_days: '',
                use_day: 0,
            }
        }
        this.currentBleCourseSn = ''
        this.performAction = 'connectOnly'
        this.laser.laserStatus = -1
        this.laser.isOpenStatus = false
        this.heart.heartStatus = false
        this.blood.bloodStatus = false
        this.shockStatus = false
        this.uploadProgress = 0
        this.connectDeviceInfo = {
            factorySerialNumber: '',
            hardwareVersion: "",
            productModle: "",
            manufacturerName: '',
            firmwareVersion: '',
            protocolStackVersion: '',
            eq: 0,
        }
        this.zHeartRateDataStatus = 0
        this.remoteInfo = {
            type: "",
            device_sn: "",
            subDevice_sn: "",
            device_code: "",
        }
        this.shockStatus = false;// 睡眠模式状态
        this.enableHeartAndBlood = false; // 获取的法规血氧心率开关状态
        this.laserPowerStatus = 1;// 获取智能激光保护协议状态
        this.isLowPattern = { modeStartNum: 0, modeEndNum: 0 };
        this.sleepDate = [0, 0, 0, 0]
        this.colockData = [0, 127, 13, 30, 0, 127, 15, 0, 0, 127, 18, 0]
        this.wifiRealUploadStatus = 0
        this.wifiTimingData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        this.offlineBleCourses = [];// 硬件当前的离线疗程
        this.courseOfflineDataLength = 0
        this.replyCount = 0
        this.isWriteOffline = false
        this.offlineActionType = 'open'
    }

    removeCallback(cb) {
        this.callbacks = this.callbacks.filter((fn) => fn !== cb);
    }
    // 注册回调
    bleCallback(cb) {
        this.callbacks.push(cb);
    }

    // 触发回调
    triggerCallbacks(res) {
        this.callbacks.forEach(cb => cb(res));
    }
    // 注册远程连接参数｜或者蓝牙连接参数
    singRemoteInfo(res) {
        this.remoteInfo = res
    }
    // 获取设备所有类型做过滤
    setDeviceTypeList(devices: DeviceType) {
        this.device.deviceTypeList = devices
    }

    bleManagerDidUpdateState(status: string) {
        this.device.deviceStatus = status == 'on' ? 1 : 0
        if (status == 'off') {
            this.device.connectDevice = {}
            if (webSocketStore.linkSubDeviceStatus == 0) {
                this.disConnectble()
            }
        }
    }

    // 获取搜索的蓝牙设备
    serachDevice(devices) {
        this.device.searchDevices = devices
        const bDeviceSnSet = new Set(userStore.userBindDeviceData.map(item => item.device_sn));
        const result = devices.filter(item => bDeviceSnSet.has(item.device_sn));
        this.bleSearchbBindDevices = result
    }
    // 断开连接
    disConnectble() {
        Bleconnect.disconnect();
        this.cleanStatus()
    }

    updateSuccessWifi(value) {
        this.successWifi = value;
    }
    // 开始连接设备
    connectBle(item, callBack) {
        Bleconnect.connect(item?.id).then((res) => {
            Bleconnect.startNotification(0);
            this.device.connectDevice = item;
            callBack && callBack({ status: 1 })
            this.performAction = 'connectOnly'
        }).catch(err => {
            callBack && callBack({ status: 2 })
        })
    }

    // 连接设备发送的协议
    async sendBleWrite(params = { type: 'ble' }) {
        syncTime();
        const tasks = [
            () => getBleEQ(params),
            () => getBleDeviceInfo(params),
            () => getBleHeartAutoState(params),
        ];
        for (const task of tasks) {
            await delay(300);
            task();
        }
    }

    // 连接设备并上传数据
    connectBleUploadData(item, callBack) {
        Bleconnect.connect(item?.id).then((res) => {
            Bleconnect.startNotification(0);
            this.device.connectDevice = item;
            this.currentCallback = callBack;
            this.performAction = 'connectAndUpload'
            // 先上传硬件数据

            getDeviceDataHead((res => {
                this.getDeviceInfo()
            }))
        }).catch(err => {
            callBack && callBack()
        })
    }
    // 获取连接的信息
    async getDeviceInfo() {
        const params = { type: 'ble' }
        try {
            const res = await getDeviceWriteInfo({ device_sn: this.device.connectDevice.device_sn })
            if (res.status !== 1) return
            this.deviceWriteInfo = res.data.deviceInfo
            syncTime();
            const tasks = [
                () => getBleEQ(params),
                () => getBleDeviceInfo(params), //  查询设备信息
                () => getBleHeartAutoState(params), // 查询自动心率开关
                () => setEbiValue(res.data.deviceInfo.eb) // 设置E币
            ];
            for (const task of tasks) {
                await delay(300);
                task();
            }
        } catch (error) {
            Toast.show({ content: '网络状况有点问题哦' })
            this.sendBleWrite({ type: 'ble' })
            this.performAction = 'connectOnly'
            if (this.currentCallback) {
                this.currentCallback(null, 0);
                this.currentCallback = null;
            }
            console.log("解析的错误", error)
        }
    }

    // 收集单条小包
    collectPacket(data) {
        if (!Array.isArray(data) || data.length < 1) return;
        // 避免重复（根据小包序号 data[1]）
        const packetIndex = data[1];
        if (!this.packets.some(p => p[1] === packetIndex)) {
            this.packets.push([...data]); // push 拷贝
        }
    }

    // 合并后的二维数组 [[小包1],[小包2],...]
    get mergedPackets() {
        return this.packets
            .slice()
            .sort((a, b) => a[1] - b[1])
            .map(p => [...p]);
    }
    connectSuccess(res) {
        // 连接蓝牙设备成功
        deviceGiveStatus({ energy: this.connectDeviceInfo.eq, device_sn: this.device.connectDevice.device_sn, firmware_sn: this.connectDeviceInfo.firmwareVersion })
        this.performAction = 'connectOnly'
        // 连接结束
        if (this.currentCallback) {
            this.currentCallback(null, res);
            this.currentCallback = null;
        }
    }
    getBleValue(res) {
        const data = res.data;
        switch (res.cmd) {
            case cmd.kGXYL_GetLaserManuallyParameters: // 查询设置的激光参数
                this.laser.power = data[4]
                this.laser.duration = data[5]
                break;
            case cmd.kGXYL_LaserManuallyParameters:  // 设置激光参数
                this.laser.laserParamsResult = data[0]
                break;
            case cmd.kGXYL_LaserIsOpen: // 打开/关闭激光
                if (this.laser.isOpenStatus) {
                    Object.assign(this.laser, {
                        laserStatus: -1,
                        laserParamsResult: -1,
                        isOpenStatus: false
                    });
                } else {
                    this.laser.laserStatus = data[0];
                    this.laser.isOpenStatus = data[0] === 0;
                }
                Toast.show({ content: this.getStatusText(data[0]) })
                break;
            case cmd.kGXYL_HRManuallyIsOpen: // 设置开启/关闭手动心率
                if (this.heart.heartStatus) {
                    Object.assign(this.heart, {
                        heartStatus: false, // 心率开启状态
                        heartValue: 0 // 心率值
                    });
                } else {
                    this.heart.heartStatus = data[0] === 0
                }
                Toast.show({ content: this.getStatusText(data[0]) })
                break;
            case cmd.kGXYL_RealtimeIsOpen:  // 获取到的心率数据
                const HR = data[4]
                if (HR !== 255 && HR !== 0) {
                    this.heart.heartValue = data[4]
                } else {
                    this.heart.heartValue = 0
                    this.heart.heartStatus = false // 心率开启状态
                }
                break;
            case cmd.kGXYL_TEREALBLOODISOPEN:  // 开关实时血压
                if (this.blood.bloodStatus) {
                    Object.assign(this.blood, {
                        bloodStatus: false,// 血压开启状态
                        systolic: 0, // 收缩压
                        diastolic: 0, // 舒张压
                        heartrate: 0, // 心率
                        microcirculation: 0, // 微循环
                    });
                } else {
                    this.blood.bloodStatus = data[0] === 0
                }
                Toast.show({ content: this.getStatusText(data[0]) })
                break;
            case cmd.kGXYL_TEREALBLOODISDATA:  // 实时血压值
                Object.assign(this.blood, {
                    bloodStatus: true,// 血压开启状态
                    systolic: res.data[0], // 收缩压
                    diastolic: res.data[1], // 舒张压
                    heartrate: res.data[2], // 心率
                    microcirculation: res.data[3], // 微循环
                });
                break;
            case cmd.kGXYL_BOLD_STATUS:  // 测量结束
                this.blood.bloodStatus = false
                break;
            case cmd.kGXYL_GETSCREENLIGHT: // 查询抬手亮屏状态设置
                this.screenStatus = res.data[0]
                break;
            case cmd.kGXYL_LaserRegimenParameters: // 写入疗程
                if (this.performAction !== 'connectAndUpload') {
                    result = { type: "setLaserParams", status: res.data[0] }
                    this.course.writeCourseStatus = res.data[0] === 0
                } else {
                    setLaserTimeOut(1)
                }
                break
            case cmd.kGXYL_SetlaserTreatmentStatus:// 疗程间隔
                if (this.performAction !== 'connectAndUpload') {
                    result = { type: "setLaserInterval", status: res.data[0] }
                    this.course.writeCourseStatus = false
                    this.course.courseIntervalStatus = res.data[0] === 0 // 疗程间隔设置成功
                } else {
                    this.connectSuccess(res)
                }
                break;
            case cmd.kGXYL_setLaserRegimen:
                if (offlineCourseDevices.indexOf(this.device.connectDevice.device_code) !== -1) {
                    if (this.isWriteOffline) {
                        this.connectSuccess(res)
                    } else {
                        this.isConnect = true
                        getLaserTreatmentParameterOnline()

                    }

                } else {
                    if (this.performAction !== 'connectAndUpload') {
                        result = { type: "setLaserRegimen", status: res.data[0] }
                    } else {
                        // 设置疗程间隙
                        const { use_day, course_cycle_work_days, course_cycle_rest_days } = this.deviceWriteInfo.course_data
                        var remaining = 0;
                        var status = 0;
                        if (Number(use_day) <= parseInt(course_cycle_work_days)) {
                            status = 1;
                            remaining = Number(course_cycle_work_days) - Number(use_day) + 1
                        } else {
                            status = 0;
                            remaining = Number(course_cycle_work_days) + Number(course_cycle_rest_days) - Number(use_day) + 1
                        }
                        LaserTreatmentInterval(remaining, { type: 'ble' }, status)
                    }
                }

                break;
            case cmd.kGXYL_GetQuerysubject: // 表盘主题下标
                this.themeIndex = res.data[0]
                break;
            case cmd.kGXYL_GetCalibration: // 校准参数查询
                this.calibration = {
                    systolic: res.data[0],
                    diastolic: res.data[1]
                }
                break;
            case cmd.kGXYL_GetAutomatictime: // 查询血压定时测量参数设置
                this.watchTimeData = res.data
                break;
            case cmd.kGXYL_GetSleep: // 血压睡眠模式参数查询
                this.bloodSleepData = res.data
                break;
            case cmd.kGXYL_TimeSync: // 同步时间
                break;
            case cmd.kGXYL_SETPOSTIONTAG: // 设置标签
                this.isTagStatus = res.data[0]
                break;
            case cmd.kGXYL_GetDeviceInfo: // 获取设备信息
                let asciiString = '';
                res.data.forEach((item) => {
                    if (this.ASCIIDic[item]) {
                        asciiString += this.ASCIIDic[item];
                    }
                });
                var array = asciiString.split('&');
                this.connectDeviceInfo = {
                    ...this.connectDeviceInfo, // 保留已有的 eq 值
                    productModle: array[0],
                    manufacturerName: array[1],
                    firmwareVersion: array[2],
                    protocolStackVersion: array[3],
                    hardwareVersion: array[4],
                    factorySerialNumber: array[5],
                }
                break;
            case cmd.kGXYL_GET_AUTO_LASER_SHOCK:// 获取睡眠模式
                this.shockStatus = res.data[0] == 0 ? true : false
                break;
            case cmd.kGXYL_GETHEARTBLOOD:// 获取的法规血氧心率开关状态
                this.enableHeartAndBlood = res.data[0] == 0 ? true : false
                break;
            case cmd.kGXYL_SETHEARTBLOOD:// 获取的法规血氧心率开关状态
                break;
            case cmd.kGXYL_GETHEARTLASER:// 开始查询智能激光输出开关状态
                this.laserPowerStatus = res.data[0]
                break;
            case cmd.kGXYL_SETHEARTLASER:// 开始查询智能激光输出开关状态
                break;
            case cmd.kGXYL_getLowerEq:// 开始查询计时返回的内容
                this.isLowPattern = {
                    modeStartNum: res.data[0] | res.data[1] << 8,
                    modeEndNum: res.data[2] | res.data[3] << 8
                };
                break;
            case cmd.kGXYL_GetEQ:
                this.connectDeviceInfo = {
                    ...this.connectDeviceInfo, // 保留已有的 eq 值
                    eq: res.data[2]
                }
                break;
            case cmd.kGXYL_GetAutoHRState:
                this.zHeartRateDataStatus = res.data[0]
                break;
            case cmd.kGXYL_HRAutomaticallIsOpen:
                getBleHeartAutoState(this.device.connectedDeviceStatus !== 0 ? { type: 'ble' } : this.remoteInfo)
                break;
            case cmd.kGXYL_GETSLEEPDATE:
                this.sleepDate = res.data
                break;
            case cmd.kGXYL_GETSLEEPDATE:
                this.sleepDate = res.data
                break;
            case cmd.kGXYL_GETSLEEPDATA:
                // 获取睡眠数据
                getHandleBleDataResponse('sleep', res.data)
                break;
            case cmd.kGXYL_GetMotionRecording:
                // 获取运动数据
                getHandleBleDataResponse('sport', res.data)
                break;
            case cmd.kGXYL_GetLaserRecording:
                // 获取激光数据
                getHandleBleDataResponse('laser', res.data)
                break;
            case cmd.kGXYL_GetHRRecording:
                // 获取心率数据
                getHandleBleDataResponse('heart', res.data)
                break;
            case cmd.kGXYL_GetHistoricalBloodPressurevalue:
                // 获取血压数据
                getHandleBleDataResponse('blood', res.data)
                break;
            case cmd.kGXYL_GETCOLOCK:
                this.colockData = res.data.length > 0 ? res.data : [0, 127, 13, 30, 0, 127, 15, 0, 0, 127, 18, 0]
                break;
            case cmd.kGXYL_LaserManuallyPayParameters:
                if (offlineCourseDevices.indexOf(this.device.connectDevice.device_code) !== -1) {
                    // 离线疗程
                    getUserOfflineCourse({ title_id: 24, device_sn: this.device.connectDevice.device_sn }).then(async res => {
                        const { code, course_data, remaining_days, status } = res
                        if (code == 200 && status == 1) {
                            if (course_data.length == 0) {
                                // 假如服务器记录的为0，那么我会从硬件拿参数
                                setLaserTimeOut(1)

                            } else {
                                this.courseOfflineDataLength = course_data.length
                                this.isWriteOffline = true
                                for (let i = 0; i < course_data.length; i++) {
                                    setLaserTreatmentParameterOnline(course_data.length, i, course_data[i])
                                    if (i < course_data.length - 1) {
                                        await delay(1500)
                                    }
                                }
                            }
                        } else {
                            Toast.show({ content: "服务异常", })
                        }
                    })
                } else {
                    if (this.deviceWriteInfo.remaining_days <= 0) {
                        // 暂停疗程,直接连接成功
                        setLaserTimeOut(0)
                        if (this.currentCallback) {
                            this.currentCallback(null, res);
                            this.currentCallback = null;
                        }
                    } else {
                        let parametersArray: any = []
                        this.deviceWriteInfo.parameter_list.forEach((v: any) => {
                            let item = {
                                power: parseInt(v.power_level),
                                duration: parseInt(v.start_duration),
                                startHour: parseInt(v.start_time.split(":")[0]),
                                startMinute: parseInt(v.start_time.split(":")[1]),
                            }
                            parametersArray.push(item);
                        })
                        let courseNumber = parseInt(this.deviceWriteInfo.course_data.course_type_sn);
                        let coursePeriodic = parseInt(this.deviceWriteInfo.course_data.course_cycle_work_days);
                        let courseGap = parseInt(this.deviceWriteInfo.course_data.course_cycle_rest_days);
                        let courseEndDate = this.deviceWriteInfo.remaining_days;
                        const dic = {
                            index: courseNumber,
                            periodic: coursePeriodic,
                            gap: courseGap,
                            endDate: courseEndDate,
                            parameters: parametersArray
                        }
                        setLaserTreatmentParameters(dic, { type: 'ble' }) // 设置疗程
                    }
                }
                break;
            case cmd.kGXYL_GetTimeUpload_Wifi:
                this.wifiTimingData = res.data
                break;
            case cmd.kGXYL_GetRealTime_Wifi:
                this.wifiRealUploadStatus = res.data[0]
                break;
            case cmd.kGXYL_GetLaserRegimenParameters:// 获取当前使用的疗程
                // 假如离线疗程
                this.currentBleCourseSn = res.data[0];
                if (this.offlineActionType !== 'stop' && this.offlineActionType !== 'switch') {
                    console.log("this.offlineBleCoursesthis.offlineBleCourses", this.offlineBleCourses[0]?.header?.endTime)
                    const today = dayjs();  // 系统当前日期
                    const endTime = this.offlineBleCourses[0]?.header?.endTime;
                    const target = dayjs(endTime);
                    const diffDays = target.diff(today, "day");
                    const courseTypeSnStr = this.offlineBleCourses.map(item => item.header.course_type_sn).join(",");
                    const obj = { device_sn: this.device.connectDevice.device_sn, course_type_sn: courseTypeSnStr, day: diffDays, use_course_type_sn: res.data[0] }
                    console.log("objobjobjobjobjobj>>>>>>>", obj)
                    writeOfflineCourse(obj).then(res => {
                        if (this.offlineActionType !== 'open') {
                            this.connectSuccess(res)
                        }
                    })
                }
                break;
            case cmd.kGXYL_SETOFFLINECORESE:// 设置离线疗程
                if (res.data[0] == 0) {
                    this.replyCount++;
                    if (this.replyCount >= this.courseOfflineDataLength) {
                        setLaserTimeOut(1)
                        this.replyCount = 0; // 清空计数器，避免下次干扰
                        this.courseOfflineDataLength = 0
                    }
                } else {
                    this.isWriteOffline = false
                    this.replyCount = 0; // 出错也要清空计数器
                    this.courseOfflineDataLength = 0
                    this.connectSuccess(res)
                }
                break;
            case cmd.kGXYL_GETOFFLINECORESEPARAMS: // 获取离线疗程
                if (res.data[0] == 4 && res.data.length == 1) {
                    const bleCourseParams = parseTherapyPacketsSeparately(this.mergedPackets)
                    console.log("bleCourseParamsbleCourseParams", bleCourseParams)
                    if (bleCourseParams.length > 0) {
                        this.offlineBleCourses = bleCourseParams
                        getBleCurrentCourse()
                    } else {
                        this.connectSuccess(res)
                    }
                    return
                }
                this.collectPacket(res.data);
                break;
            case cmd.kGXYL_SWITCHOFFLINECOURSESN: // 切换离线疗程
                result = { type: "kGXYL_SWITCHOFFLINECOURSESN", status: res.data[0] }
                console.log("切换离线疗程", res.data)
                break;
            case cmd.kGXYL_GetlaserTreatmentStatus:
                this.bleDeviceCourseStatus = res.data[0]
                break;
            default:
                break;
        }
        // 如果有回调，调用回调
        if (result) {
            this.triggerCallbacks(result);
        }
    }
}

export default new DeviceStore();